package com.authine.cloudpivot.web.api.controller;



import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.AttachmentModel;
import com.authine.cloudpivot.engine.enums.type.FileUploadType;
import com.authine.cloudpivot.web.api.controller.base.PermissionController;
import com.authine.cloudpivot.web.api.controller.common.OSSController;
import com.authine.cloudpivot.web.api.domain.dto.AttachmentDTO;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.exception.ResultEnum;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import com.authine.cloudpivot.web.api.oss.FileStorageConfiguration;
import com.authine.cloudpivot.web.api.oss.OSSClient;
import com.authine.cloudpivot.web.api.service.AttachmentsService;
import com.authine.cloudpivot.web.api.sftp.SFTPClient;
import com.authine.cloudpivot.web.api.util.ImageUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.system.FontTextVO;
import com.authine.cloudpivot.web.api.view.system.OssConfigVO;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Api(
        value = "文件上传",
        tags = {"系统管理::文件上传下载接口"}
)
@Controller
@RequestMapping({"/api/attachments"})
@CustomizedOrigin(
        level = 0
)
public class AttachmentsController extends PermissionController {
    private static final Logger log = LoggerFactory.getLogger(OSSController.class);
    public static final String STORAGE_METHOD_OSS = "oss";
    private static final String KEY_WORKFLOW_ATTACHMENT = "cloudpivot:fileupload:workflow_attachment";
    private static final String MIMETYPE_SUFFIX = "application/";
    private static final String IMAGE_SUFFIX = "image/";
    private static final String PIC_EXTENSION = ".jpg.JPG.png.PNG.jpeg.JPEG";
    private static final String[] IGNORE_FILE_TYPES = new String[]{".php", ".php5", ".php4", ".php3", ".php2", ".php1", ".html", ".htm", ".phtml", ".pHp", ".pHp5", ".pHp4", ".pHp3", ".pHp2", ".pHp1", ".Html", ".Htm", ".pHtml", ".jsp", ".jspa", ".jspx", ".jsw", ".jsv", ".jspf", ".jtml", ".jSp", ".jSpx", ".jSpa", ".jSw", ".jSv", ".jSpf", ".jHtml", ".asp", ".aspx", ".asa", ".asax", ".ascx", ".ashx", ".asmx", ".cer", ".aSp", ".aSpx", ".aSa", ".aSax", ".aScx", ".aShx", ".aSmx", ".cEr", ".sWf", ".swf"};
    private static List<String> FILE_TYPE_WHITE_LIST = Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".tif", ".docx", ".xlsx", ".pptx", ".doc", ".xls", ".ppt", ".wpt", ".dot", ".rtf", ".txt", ".xml", ".pdf", ".rar", ".zip", ".MP3", ".WMA", ".WAV", ".MIDI", ".CDA", ".VI", ".mov", ".rmvb", ".rm", ".FLV", ".mp4", ".3GP");
    @Autowired
    private OSSClient ossClient;
    @Autowired
    private SFTPClient sftpClient;
    @Autowired
    private RedisTemplate<String, AttachmentModel> redisTemplate;
    @Value("${cloudpivot.attachment.fileTypes:}")
    private String extendFileTypes;
    @Autowired
    private AttachmentsService attachmentsService;
    @Autowired
    public HttpServletRequest request;

    public AttachmentsController() {
    }

    public static String[] getFileInfo(String fileName) {
        int index = fileName.lastIndexOf(".");
        String toPrefix = "";
        String toSuffix = "";
        if (index == -1) {
            toPrefix = fileName;
        } else {
            toPrefix = fileName.substring(0, index);
            toSuffix = fileName.substring(index, fileName.length());
        }

        return new String[]{toPrefix, toSuffix};
    }

    @PostConstruct
    public void init() {
        if (StringUtils.isNotEmpty(this.extendFileTypes)) {
            String[] split = this.extendFileTypes.split(",");
            ArrayList<String> whiteList = Lists.newArrayList();
            whiteList.addAll(Arrays.asList(split));
            whiteList.addAll(FILE_TYPE_WHITE_LIST);
            FILE_TYPE_WHITE_LIST = whiteList;
        }

    }

    @PostMapping({"/upload"})
    @ResponseBody
    @ApiOperation("oss 文件上传接口,注意：key 用 file")
    public ResponseResult<AttachmentModel> upload(@RequestParam MultipartFile file, Boolean isAddWatermark, String locationInfo, String fileName) throws Exception {
        if (StringUtils.isEmpty(fileName)) {
            fileName = file.getOriginalFilename();
        }

        this.checkFileType(fileName);
        String fileNameTemplate = null;

        try {
            if (!Strings.isNullOrEmpty(fileName)) {
                log.debug(fileName);
                String suffix = fileName.substring(fileName.lastIndexOf(46) + 1);
                String refId = UUID.randomUUID().toString().replace("-", "");
                fileNameTemplate = refId.concat(fileName);
                byte[] targetBytes = null;
                Boolean isPic = this.checkImageFile(file);
                if (log.isDebugEnabled()) {
                    log.debug("isPic = {}, isAddWatermark = {}, locationInfo = {}", new Object[]{isPic, isAddWatermark, locationInfo});
                }

                if (isPic && isAddWatermark != null && isAddWatermark) {
                    String userId = this.getUserId();
                    UserModel user = this.getOrganizationFacade().getUser(userId);
                    String userName = user == null ? "" : user.getName();
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    if (StringUtils.isNotEmpty(locationInfo) && locationInfo.length() > 40) {
                        locationInfo = locationInfo.substring(0, 40) + "...";
                    }

                    targetBytes = ImageUtils.drawTextInImg(file.getBytes(), new FontTextVO(Lists.newArrayList(new String[]{now.format(dateTimeFormatter) + " " + userName, locationInfo}), 9, "#FFFFFF", 24, "SimHei", 0.0D, 0.64F),0);
                    if (log.isDebugEnabled()) {
                        log.debug("drawTextInImg is finished....");
                    }
                }

                if (FileStorageConfiguration.getFileUploadType() == FileUploadType.OSS) {
                    log.debug("the upload type is sso");
                    File newFile = new File(fileNameTemplate);
                    FileOutputStream os = FileUtils.openOutputStream(newFile);
                    if (isPic && isAddWatermark != null && isAddWatermark) {
                        os.write(targetBytes);
                    } else {
                        os.write(file.getBytes());
                    }

                    os.close();
                    this.ossClient.fileUpload(refId, newFile);
                    newFile.delete();
                } else {
                    log.info("the upload type is sftp");

                    try {
                        if (targetBytes == null) {
                            targetBytes = file.getBytes();
                        }

                        this.sftpClient.uploadFile(fileNameTemplate, new ByteArrayInputStream(targetBytes));
                    } catch (Exception var15) {
                        log.error("", var15);
                        throw var15;
                    }
                }

                AttachmentModel resourceModel = new AttachmentModel();
                resourceModel.setRefId(refId);
                resourceModel.setName(fileName);
                resourceModel.setFileExtension(".".concat(suffix));
                resourceModel.setFileSize((new Long(file.getSize())).intValue());
                if (".jpg.JPG.png.PNG.jpeg.JPEG".contains(suffix)) {
                    if (".jpg.JPG".contains(suffix)) {
                        suffix = "jpeg";
                    }

                    resourceModel.setMimeType("image/".concat(suffix));
                } else {
                    resourceModel.setMimeType("application/".concat(suffix));
                }

                this.redisTemplate.boundHashOps("cloudpivot:fileupload:workflow_attachment").putIfAbsent(refId, resourceModel);
                this.redisTemplate.expire("cloudpivot:fileupload:workflow_attachment", 24L, TimeUnit.HOURS);
                return this.getOkResponseResult(resourceModel, "文件上传成功");
            }
        } catch (IOException var16) {
            log.error(var16.getMessage());
            throw new PortalException(ResultEnum.OSS_UPLOAD_ERR.getErrCode(), ResultEnum.OSS_UPLOAD_ERR.getErrMsg());
        }

        throw new PortalException(ResultEnum.OSS_UPLOAD_ERR.getErrCode(), ResultEnum.OSS_UPLOAD_ERR.getErrMsg());
    }

    private void checkFileType(String fileName) throws Exception {
        String suffix = fileName.substring(fileName.lastIndexOf(46));
        if (StringUtils.isEmpty(suffix)) {
            throw new Exception(ResultEnum.FILE_TYPE_ILLEGAL.getErrCode() + "-" + ResultEnum.FILE_TYPE_ILLEGAL.getErrMsg());
        } else {
            boolean contain = FILE_TYPE_WHITE_LIST.contains(suffix) || FILE_TYPE_WHITE_LIST.contains(suffix.toLowerCase()) || FILE_TYPE_WHITE_LIST.contains(suffix.toUpperCase());
            if (!contain) {
                throw new Exception(ResultEnum.FILE_TYPE_ILLEGAL.getErrCode() + "-" + ResultEnum.FILE_TYPE_ILLEGAL.getErrMsg());
            } else {
                String[] var4 = IGNORE_FILE_TYPES;
                int var5 = var4.length;

                for(int var6 = 0; var6 < var5; ++var6) {
                    String illegal = var4[var6];
                    boolean containsIllegal = fileName.contains(illegal) || fileName.contains(illegal.toLowerCase()) || fileName.contains(illegal.toUpperCase());
                    if (containsIllegal) {
                        throw new Exception(ResultEnum.FILE_TYPE_ILLEGAL.getErrCode() + "-" + ResultEnum.FILE_TYPE_ILLEGAL.getErrMsg());
                    }
                }

            }
        }
    }

    private Boolean checkImageFile(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            BufferedImage bi = ImageIO.read(inputStream);
            if (bi != null) {
                return Boolean.TRUE;
            }
        } catch (Exception var4) {
            log.debug("检查图片时异常, e = {}", var4);
            return Boolean.FALSE;
        }

        return Boolean.FALSE;
    }

    @GetMapping({"/download"})
    @ResponseBody
    @ApiOperation("oss 文件下载接口")
    @ApiImplicitParam(
            name = "refId",
            value = "资源id",
            required = true,
            dataType = "String",
            paramType = "query"
    )
    public void download(@RequestParam String refId, HttpServletResponse response) {
        this.validateNotEmpty(refId, "refId 不能为空");
        String fileName;
        if (refId.contains(".") && FileStorageConfiguration.getFileUploadType() == FileUploadType.FTP) {
            response.setCharacterEncoding(Charsets.UTF_8.name());
            String suffix = refId.substring(refId.lastIndexOf(46) + 1);
            if (".jpg.JPG.png.PNG.jpeg.JPEG".contains(suffix)) {
                if (".jpg.JPG".contains(suffix)) {
                    suffix = "jpeg";
                }

                response.setContentType("image/".concat(suffix));
            } else {
                response.setContentType("application/".concat(refId.substring(refId.lastIndexOf(46) + 1)));
            }

            try {
                fileName = this.request.getHeader("User-Agent").toUpperCase();
                Boolean flag = fileName.contains("MSIE") || fileName.contains("TRIDENT") || fileName.contains("EDGE");
                if (flag) {
                    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(refId, "UTF-8"));
                } else {
                    response.setHeader("Content-Disposition", "attachment; filename=" + new String(refId.getBytes("utf-8"), "ISO8859-1"));
                }

                this.sftpClient.downloadFile(refId, response);
            } catch (Exception var16) {
                var16.printStackTrace();
            }

        } else {
            AttachmentModel resourceModel = this.getBizObjectFacade().getAttachmentByRefId(refId);
            if (resourceModel == null) {
                Object object = this.redisTemplate.boundHashOps("cloudpivot:fileupload:workflow_attachment").get(refId);
                resourceModel = (AttachmentModel)object;
            }

            if (resourceModel == null) {
                throw new PortalException(ResultEnum.OSS_DOWNLOAD_PERMISSION_ERR.getErrCode(), ResultEnum.OSS_DOWNLOAD_PERMISSION_ERR.getErrMsg());
            } else {
                String ossKey;
                if (FileStorageConfiguration.getFileUploadType() == FileUploadType.OSS) {
                    log.debug("the download type is sso");
                    OSS client = null;

                    try {
                        ossKey = resourceModel.getRefId();
                        OssConfigVO ossConfig = this.ossClient.getOssConfig();
                        client = this.ossClient.getClient(ossConfig);
                        OSSObject ossObject = client.getObject(ossConfig.getBucket(), ossKey);
                        if (ossObject == null) {
                            throw new PortalException(ResultEnum.OSS_UPLOAD_ERR.getErrCode(), "OSS 文件不存在：refId=".concat(ossKey));
                        }

                        InputStream inputStream = ossObject.getObjectContent();
                        response.setCharacterEncoding(Charsets.UTF_8.name());
                        response.setContentType(resourceModel.getMimeType());
                        response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(resourceModel.getName(), "UTF-8"));
                        IOUtils.copy(inputStream, response.getOutputStream());
                    } catch (IOException var14) {
                        log.error("文件下载失败: {}", var14.getMessage());
                        throw new PortalException(ResultEnum.OSS_UPLOAD_ERR.getErrCode(), ResultEnum.OSS_UPLOAD_ERR.getErrMsg());
                    } finally {
                        if (client != null) {
                            client.shutdown();
                        }

                    }
                } else {
                    log.debug("the download type is sftp");
                    fileName = resourceModel.getRefId().concat(resourceModel.getName());
                    response.setCharacterEncoding(Charsets.UTF_8.name());
                    response.setContentType(resourceModel.getMimeType());

                    try {
                        ossKey = this.request.getHeader("User-Agent").toUpperCase();
                        Boolean flag = ossKey.contains("MSIE") || ossKey.contains("TRIDENT") || ossKey.contains("EDGE");
                        if (flag) {
                            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(resourceModel.getName(), "UTF-8"));
                        } else {
                            response.setHeader("Content-Disposition", "attachment; filename=" + new String(resourceModel.getName().getBytes("utf-8"), "ISO8859-1"));
                        }

                        this.sftpClient.downloadFile(fileName, response);
                    } catch (Exception var17) {
                        log.error("", var17);
                    }
                }

            }
        }
    }


    @ApiOperation(value = "校验是否存在附件" )
    @GetMapping("/checkAttachments")
    @ResponseBody
    public ResponseResult<?> checkAttachments(String projectNo, String settleable, String storeRotation, String storeNum,String startTime, String endTime, String member, String cityName) {
        JSONObject json = new JSONObject();
        Long statusReal = 200L;
        try {
            startTime= changTime(startTime);
            endTime= changTime(endTime);
            List<AttachmentDTO> attachmentDTOList=attachmentsService.getMultiVO(projectNo, settleable, storeRotation, storeNum, startTime,endTime,  member, cityName);
             if(ObjectUtil.isNotNull(attachmentDTOList)){
                JSONArray appFunctionName = JSONArray.fromObject(attachmentDTOList);
                json.put("attachmentDTOList",appFunctionName);
             }
            json.put("message","校验项目问卷附件成功");
        }catch (PortalException e) {
            statusReal = 500L;
            json.put("message", "校验项目问卷附件失败：" + e.getErrMsg());
        }
        return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
    }

    /**
     * @Description : 时间格式转换
     * @param ： time
     * @author : Liun
     * @date : 2020/7/20
     */
    private String changTime(String time) {
        try {
            if(StringUtils.isNotEmpty(time)){
                time= time.replace("Z", " UTC");
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                Date date = df.parse(time);
                SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
                Date date1 = df1.parse(date.toString());
                DateFormat  df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                time= df2.format(date1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }



    @GetMapping({"/download_multi"})
    @ResponseBody
    @ApiOperation("oss 文件批量下载接口")
    public void multiDownload(String projectNo,String projectName,String settleable,String storeRotation,String storeNum,String startTime, String endTime,String member,String cityName, HttpServletRequest request, HttpServletResponse response) {
        startTime= changTime(startTime);
        endTime= changTime(endTime);
        //根据项目查找附件
        List<AttachmentDTO> attachmentDTOList=attachmentsService.getMultiVO(projectNo, settleable, storeRotation,storeNum,startTime, endTime, member,cityName);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < attachmentDTOList.size(); i++) {
            //查询到对应的附件id
            sb.append(attachmentDTOList.get(i).getRefId());
            if (i < attachmentDTOList.size() - 1) {
                sb.append(",");
            }
        }
        String multiVO=sb.toString();

        if (StringUtils.isEmpty(multiVO)) {
            throw new PortalException(ResultEnum.OSS_DOWNLOAD_ERR.getErrCode(), ResultEnum.OSS_DOWNLOAD_ERR.getErrMsg());
        } else {
            List<String> refIds = Arrays.asList(multiVO.split(","));
            String userId = this.getUserId();
            if (Strings.isNullOrEmpty(userId)) {
                throw new PortalException(ResultEnum.GET_USERINFO_ERR.getErrCode(), ResultEnum.GET_USERINFO_ERR.getErrMsg());
            } else {
                OSS client = null;
                String zipSuffix = ".zip";
                BufferedOutputStream out = null;
                BufferedInputStream buff = null;
                FileInputStream fis = null;
                File zipFile = null;
                ChannelSftp sftp = null;

                try {
                    //String prefix = UUID.randomUUID().toString();
                    String prefix =projectName;
                    String zipFileName = prefix.concat(zipSuffix);
                    zipFile = File.createTempFile(prefix, zipSuffix);
                    FileOutputStream f = new FileOutputStream(zipFile);
                    CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
                    ZipOutputStream zos = new ZipOutputStream(csum);
                    Map<String, AttachmentModel> attachmentModelMap = Maps.newHashMap();
                    List<String> fileNames = new ArrayList();
                    Iterator var20 = refIds.iterator();

                    String refId;
                    while(var20.hasNext()) {
                        refId = (String)var20.next();
                        AttachmentModel resourceModel = null;
                        Object object = this.redisTemplate.boundHashOps("cloudpivot:fileupload:workflow_attachment").get(refId);
                        resourceModel = object == null ? null : (AttachmentModel)object;
                        if (resourceModel == null) {
                            resourceModel = this.getBizObjectFacade().getAttachmentByRefId(refId);
                        }

                        if (resourceModel == null) {
                            throw new PortalException(ResultEnum.OSS_DOWNLOAD_PERMISSION_ERR.getErrCode(), ResultEnum.OSS_DOWNLOAD_PERMISSION_ERR.getErrMsg());
                        }

                        attachmentModelMap.put(refId, resourceModel);
                    }

                    if (FileStorageConfiguration.getFileUploadType() == FileUploadType.FTP) {
                        sftp = this.sftpClient.createSftp();
                    } else {
                        OssConfigVO ossConfig = this.ossClient.getOssConfig();
                        client = this.ossClient.getClient(ossConfig);
                    }

                    for(var20 = refIds.iterator(); var20.hasNext(); zos.closeEntry()) {
                        refId = (String)var20.next();
                        InputStream inputStream = null;
                        AttachmentModel attachmentModel = (AttachmentModel)attachmentModelMap.get(refId);
                        if (FileStorageConfiguration.getFileUploadType() == FileUploadType.OSS) {
                            OssConfigVO ossConfig = this.ossClient.getOssConfig();
                            OSSObject ossObject = client.getObject(ossConfig.getBucket(), refId);
                            if (ossObject == null) {
                                throw new PortalException(ResultEnum.OSS_UPLOAD_ERR.getErrCode(), "OSS 文件不存在：refId=".concat(refId));
                            }

                            log.debug("the batch download type is oss");
                            inputStream = ossObject.getObjectContent();
                        } else {
                            log.debug("the batch download type is sftp");
                            String fileName = refId.concat(attachmentModel.getName());

                            try {
                                inputStream = sftp.get(this.sftpClient.getFileName(fileName));
                            } catch (SftpException var37) {
                                log.error("", var37);
                            }
                        }

                        this.parseFileNames(fileNames, attachmentModel,attachmentDTOList);
                        zos.putNextEntry(new ZipEntry(attachmentModel.getName()));
                        if (inputStream != null) {
                            int bytesRead;
                            while((bytesRead = inputStream.read()) != -1) {
                                zos.write(bytesRead);
                            }

                            inputStream.close();
                        }
                    }

                    zos.close();
                    String header = request.getHeader("User-Agent").toUpperCase();
                    zipFileName = this.getDisposition(zipFileName);
                    response.reset();
                    response.setContentType("text/plain");
                    response.setContentType("application/octet-stream; charset=utf-8");
                    response.setHeader("Location", zipFileName);
                    response.setHeader("Cache-Control", "max-age=0");
                    response.setHeader("Content-Disposition", "attachment; filename=".concat(zipFileName));
                    fis = new FileInputStream(zipFile);
                    buff = new BufferedInputStream(fis);
                    out = new BufferedOutputStream(response.getOutputStream());
                    byte[] car = new byte[1024];
                    int length = 0;

                    while((long)length < zipFile.length()) {
                        int j = buff.read(car, 0, 1024);
                        length += j;
                        out.write(car, 0, j);
                    }
                } catch (IOException var38) {
                    log.error("", var38);
                    throw new PortalException(ResultEnum.OSS_DOWNLOAD_ERR.getErrCode(), ResultEnum.OSS_DOWNLOAD_ERR.getErrMsg());
                } finally {
                    try {
                        if (sftp != null) {
                            this.sftpClient.disconnect(sftp);
                        }
                    } catch (Exception var36) {
                        log.error(var36.getMessage(), var36);
                    }

                    if (zipFile != null) {
                        zipFile.delete();
                    }

                    try {
                        if (fis != null) {
                            fis.close();
                        }

                        if (buff != null) {
                            buff.close();
                        }

                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException var35) {
                        log.error(var35.getMessage());
                    }

                    if (client != null) {
                        client.shutdown();
                    }

                }

            }
        }
    }

    public String getDisposition(String fileName) {
        String headerValue = "attachment;";
        headerValue = headerValue + " filename=\"" + this.encodeURIComponent(fileName) + "\";";
        headerValue = headerValue + " filename*=utf-8''" + this.encodeURIComponent(fileName);
        return headerValue;
    }

    public String encodeURIComponent(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException var3) {
            return null;
        }
    }

    private void parseFileNames(List<String> fileNames, AttachmentModel resourceModel,List<AttachmentDTO> attachmentDTOList) {
        //附件重命名
        for(AttachmentDTO attachmentDTO:attachmentDTOList){
            if(attachmentDTO.getName().equals(resourceModel.getName())){
                resourceModel.setName(attachmentDTO.getLastName());
            }
        }

        String fileName = null;
        String[] fileInfo = getFileInfo(resourceModel.getName());
        String toPrefix = fileInfo[0];
        String toSuffix = fileInfo[1];

        //相同名称时排序
        for(int i = 1; fileNames.contains(resourceModel.getName()); ++i) {
            log.debug("文件名为{}", resourceModel.getName());
            fileName = toPrefix + "(" + i + ")" + toSuffix;
            resourceModel.setName(fileName);
        }

        fileNames.add(resourceModel.getName());
    }
}

